package demo.practice.double_pointer;

public class Offer21 {
    public static void main(String[] args) {
        Offer21 offer21 = new Offer21();
        offer21.exchange(new int[]{1, 3, 5});
    }

    public int[] exchange(int[] nums) {
        int i = 0;
        int j = nums.length - 1;

        while (i < j) {
            while (i < nums.length && (nums[i] & 1) == 1) {
                i++;
            }
            while (j >= 0 && (nums[j] & 1) == 0) {
                j--;
            }

            if (i < j) {
                swap(nums, i, j);
            }
        }
        return nums;
    }

    private void swap(int[] nums, int i, int j) {
        if (i == j) //如果i==j，直接会当前元素更改为0，并且两个位置重合，就会直接变成0，造成错误
        {
            return;
        }
        nums[i] = nums[i] ^ nums[j];
        nums[j] = nums[i] ^ nums[j];
        nums[i] = nums[i] ^ nums[j];
    }


}
